package 优先算法.递归_搜索与回溯.综合案列.全排列2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = {1, 1, 2};
        List<List<Integer>> result = solution.permuteUnique(nums);
        for (List<Integer> permutation : result) {
            System.out.println(permutation);
        }
    }
}
class Solution {
    public  List<Integer> path;
    public  List<List<Integer>> ret;
    boolean[] check;
    public List<List<Integer>> permuteUnique(int[] nums) {
        ret = new ArrayList<>();
        path = new ArrayList<>();
        check = new boolean[nums.length];
        Arrays.sort(nums); // 先对nums进行排序，保证每一组的元素都不相同
        dfs(nums, 0);
        return ret;
    }

    private void dfs(int[] nums, int pos) {
        if(pos == nums.length){
            ret.add(new ArrayList<>(path));
            return ;
        }
        for(int i = 0 ; i < nums.length; i++){
            if (check[i] == true || (i != 0 && nums[i] == nums[i-1] && !check[i-1]))
                continue;

            path.add(nums[i]);
            check[i] = true;
            dfs(nums,pos + 1);
            path.remove(path.size()-1);
            check[i] = false;
        }
    }
}